package com.example.agent_springai.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    
    private static final DateTimeFormatter[] FORMATTERS = {
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
        DateTimeFormatter.ISO_LOCAL_DATE_TIME,
        DateTimeFormatter.ISO_DATE_TIME
    };
    
    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateString = p.getText();
        if (dateString == null || dateString.isEmpty()) {
            return null;
        }
        
        // 移除末尾的.000Z等毫秒和时区信息，如果有的话
        if (dateString.contains(".")) {
            int dotIndex = dateString.indexOf('.');
            if (dotIndex > 0) {
                dateString = dateString.substring(0, dotIndex);
            }
        }
        
        for (DateTimeFormatter formatter : FORMATTERS) {
            try {
                return LocalDateTime.parse(dateString, formatter);
            } catch (DateTimeParseException e) {
                // Continue to next formatter
            }
        }
        
        // 如果我们自定义的格式都无法解析，尝试使用默认的LocalDateTimeDeserializer
        try {
            return LocalDateTimeDeserializer.INSTANCE.deserialize(p, ctxt);
        } catch (Exception e) {
            // 如果所有方法都失败，则抛出异常
            throw new DateTimeParseException("Unable to parse date time: " + dateString, dateString, 0);
        }
    }
}